<?php


namespace App\Middleware\Auth;

use App\Server\Model\AdminGroup;
use App\Server\Model\AdminMenu;
use Hyperf\HttpMessage\Cookie\Cookie;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Exception\ValidateException;
use Hyperf\Utils\Context;
use App\Common\Controller\AbstractController;


class Admin extends AbstractController implements MiddlewareInterface
{

    /**
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @param \Psr\Http\Server\RequestHandlerInterface $handler
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \App\Exception\ValidateException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 是否登录
        if($this->session->get('admin') == false)
        {
            if($this->request->cookie('admin')) {
                $cookie = new Cookie('admin', $this->request->cookie('admin'));
            }
            if (isset($cookie)){
                $name = unserialize($this->request->cookie('admin'));
                $this->session->set('admin',$name);
                return $this->response->redirect('admin/index/index');
            }else{
                return $this->response->redirect('admin/common/login');
            }
        }

        $admin_session = $this->session->get('admin');
        $adminModel = new \App\Server\Model\Admin();
        $adminInfo = $adminModel -> getCacheInfo([['id','=',$admin_session['id']]], 'admin_info_id_'.$admin_session['id']);
        Context::set('adminInfo', $adminInfo);

        // 被封禁
        $Webconfig = new \App\Server\Model\Webconfig();
        $web_config = $Webconfig->getCacheInfo([['config_key','=','web']],'webconfig_web');
        if(!empty($web_config['black_ip'])) {
            //转化成数组
            $black_ip = explode(',',$web_config['black_ip']);
            //获取当前访问的ip
            $ip = getClientIp();
            if(in_array($ip,$black_ip)) {
                $this->session->clear();
                $cookie = new Cookie('admin', '');
                return $this->error('你已被封禁！',['url'=>'/admin/common/login'])->withCookie($cookie);
            }
        }
        if ($admin_session['id']!=1){
            // 验证当前菜单是否有权限
            $router = $this->request->getRequestUri();
            $adminMenuModel = new AdminMenu();
            $menus = $adminMenuModel->getCacheList([],'menu_all');
            $menus = array_column($menus,null,'router');
            $menus_info = $menus[$router];
            if ($menus_info['type'] == 1){
                $adminGroup = new AdminGroup();
                $uGroupIds = explode(',',$adminModel->getValue([['id','=',$adminInfo['id']]],'groups'));
                $where = [];
                $where[] = ['status','=',1];
                $where['whereIn'] = ['id',$uGroupIds];
                $uRuleIds  = $adminGroup->getList($where,['rules']);
                $uRules = [];
                foreach ($uRuleIds as $k => $v) {
                    if (!empty($v['rules'])){
                        $uRules = array_unique(array_merge($uRules,explode(',',$v['rules'])));
                    }
                }
                if (!in_array($menus_info['id'],$uRules)){
                    return $this->error('没有操作权限！');
                }
            }
        }
        return $handler->handle($request);
    }
}